package com.banciyuan.bcywebview.biz.post.write;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ChooseDialog;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.post.Listener.OnTextChangeListener;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DraftsPostItem;
import de.greenrobot.daoexample.model.PostItem;

/**
 * Created by hy on 2015/12/31.
 */
public class WriteArticleActivity extends BaseActivity implements ActionbarHelper.OnActionCallbacks, View.OnClickListener {
    protected static final int GO_POSTWRITE = 100;
    protected EditText articleTitle;
    protected EditText articleContent;
    private TextView titleLimit;
    private TextView contentLimit;
    private String CONTENT_FORMAT = "%d字";
    private String TITLE_FORMAT = "%d/30";
    private String TITLE_CONTENT_FORMAT = "%s(%d)";
    private View mActionBarView;
    protected ActionbarHelper mActionbarHelper;
    private TextView tv_save;
    private String chapterCount;
    private String chapterTitle = "";
    protected PostItem postItem = new PostItem();
    private String type = "fanfic";
    private String work = "";
    protected String tag = "";
    protected View mProgressbarView;
    protected ProgressbarHelper mProgressbarHelper;
    protected RequestQueue mQueue;
    protected List<String> tag_array = new ArrayList<String>();
    protected boolean edit = false;
    protected boolean init = false;
    private DraftsPostItem modifyDraftsItem;
    private String uid;
    private List<DraftsPostItem> novelDrafts;
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.write_article_layout);
        initArgs();
        initUi();
        initActionbar();
        initProgressbar();
        initAction();
        if (!edit) {
            initData();
        }
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        Intent intent = getIntent();
        chapterTitle = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        chapterCount = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        type = intent.getStringExtra(gotoUtil.INTENT_VALUE_THREE);
        work = intent.getStringExtra(gotoUtil.INTENT_VALUE_FOUR);
        tag = intent.getStringExtra("tags");
        tag_array = (List<String>) intent.getSerializableExtra("tag_array");
        String wns_id = intent.getStringExtra(gotoUtil.INTENT_VALUE_FIVE);
        postItem.setWns_id(wns_id);
        postItem.setType(type);
        postItem.setWork(work);
        postItem.setCover(intent.getStringExtra(gotoUtil.INTENT_VALUE_SIX));

        if (!TextUtils.isEmpty(tag)) {
            postItem.getOptional().getTags().add(tag);
        }
        if (tag_array != null && !tag_array.isEmpty()) {
            postItem.getOptional().getTags().addAll(tag_array);
        }
        if (!TextUtils.isEmpty(chapterTitle) && !TextUtils.isEmpty(chapterCount)) {
            postItem.setTitle(String.format(TITLE_CONTENT_FORMAT, chapterTitle, Integer.parseInt(chapterCount) + 1));
        }
        if (null != intent.getSerializableExtra("drafts_postitem") && intent.getSerializableExtra("drafts_postitem") instanceof DraftsPostItem) {
            modifyDraftsItem = (DraftsPostItem) intent.getSerializableExtra("drafts_postitem");
            postItem = modifyDraftsItem.getPostItem();
        }

        uid = UserDataHelper.getInstance(WriteArticleActivity.this).getUid();
        String novelDraftsStr = SPHelper.getString(WriteArticleActivity.this, SPConstant.SPNAME_NOVELDRAFTS + uid, SPConstant.NOVEL, "[]");
        gson = new Gson();
        novelDrafts = gson.fromJson(novelDraftsStr, new TypeToken<List<DraftsPostItem>>() {
        }.getType());
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi() {
        articleTitle = (EditText) findViewById(R.id.et_article_title);
        articleContent = (EditText) findViewById(R.id.et_article_content);
        titleLimit = (TextView) findViewById(R.id.tv_title_limit);
        contentLimit = (TextView) findViewById(R.id.tv_content_limit);
        if (!TextUtils.isEmpty(postItem.getTitle())) {
            articleTitle.setText(postItem.getTitle());
            titleLimit.setText(String.format(TITLE_FORMAT, articleTitle.getText().toString().length()));
            articleContent.requestFocus();
        }
        if (null != postItem.getContent() && postItem.getContent().size() > 0) {
            StringBuffer sb = new StringBuffer();
            for (String s : postItem.getContent()) {
                sb.append(Html.fromHtml(s) + "\n");
            }
            articleContent.setText(sb);
        }
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.write_article));
        mActionbarHelper.addItemOneText(getString(R.string.next));
        mActionbarHelper.addBackText(getString(R.string.mydialog_cancel));
        mActionbarHelper.setActionCallbacks(this);
        tv_save = (TextView) findViewById(R.id.base_action_bar_home_text_item);
        tv_save.setOnClickListener(this);
    }

    @Override
    protected void initAction() {
        articleTitle.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable editable) {
                showTitleLength(editable.toString().length());
            }
        });

        articleContent.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable editable) {
                showContentLength(editable.toString().length());
            }
        });
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + NovelApi.getUploadparam();
        List<BcyPair> pairList = new ArrayList<BcyPair>();
        pairList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        Map<String, String> map = HttpUtils.getData(pairList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                    if (result.has("wp_id")) {
                        postItem.setWp_id(result.getString("wp_id"));
                    }
                    if (result.has("post_token")) {
                        postItem.setPost_token(result.getString("post_token"));
                    }
                    mProgressbarHelper.onSuccess();
                } catch (JSONException e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };

        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(stringRequestParam);
    }

    protected void showContentLength(int contentLength) {
        if (contentLength == 0)
            contentLimit.setText("");
        else
            contentLimit.setText(String.format(CONTENT_FORMAT, contentLength));
    }

    protected void showTitleLength(int titleLength) {
        if (titleLength == 0)
            titleLimit.setText("");
        else
            titleLimit.setText(String.format(TITLE_FORMAT, titleLength));
    }

    protected boolean checkSaveButton() {
        if (TextUtils.isEmpty(articleTitle.getText().toString().trim())) {
            MyToast.show(WriteArticleActivity.this, getString(R.string.title_cant_benull));
            return false;
        }
        if (TextUtils.isEmpty(articleContent.getText().toString().trim())) {
            MyToast.show(WriteArticleActivity.this, getString(R.string.content_cant_benull));
            return false;
        }
        return true;
    }


    @Override
    public void onBackClick() {
        if (checkNeedSave()) {
            finishActivity();
        } else {
            finish();
        }
    }

    @Override
    public void onActionClick(int id) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_action_bar_home_text_item:
                if (checkSaveButton()) {
                    getPostJson();
                    Intent intent = new Intent(this, WritePostActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, postItem);
                    startActivityForResult(intent, GO_POSTWRITE);
                }
                break;
        }
    }

    protected void getPostJson() {
        String content = articleContent.getText().toString().trim();
        String[] contents = content.split("\n");
        List<String> listContent = Arrays.asList(contents);
        postItem.setContent(listContent);
        postItem.setTitle(articleTitle.getText().toString().trim());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GO_POSTWRITE) {
            if (resultCode == RESULT_OK) {
                deleteModifyDraftsItem();
                if (null != modifyDraftsItem) {
                    SPHelper.putString(WriteArticleActivity.this, SPConstant.SPNAME_NOVELDRAFTS + uid, SPConstant.NOVEL, gson.toJson(novelDrafts));
                    SPHelper.putString(WriteArticleActivity.this, SPConstant.SPNAME_NOVELDRAFTS + uid, SPConstant.NOVEL_COUNT, String.valueOf(novelDrafts.size()));
                }
                setResult(RESULT_OK);
                finish();
            } else {
                postItem = (PostItem) data.getSerializableExtra("postitem");
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (checkNeedSave()) {
            finishActivity();
        } else {
            finish();
        }
    }

    private void finishActivity() {
        ChooseDialog.Builder builder = new ChooseDialog.Builder(this);
        builder.setChooseOneString(getString(R.string.save_drafts))
                .setChooseTwoString(getString(R.string.no_save))
                .setChooseOneClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        saveDrafts();
                    }
                })
                .setChooseTwoClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).create().show();

    }

    private void saveDrafts() {
        DraftsPostItem draftsPostItem = new DraftsPostItem();
        draftsPostItem.setPostItem(postItem);
        draftsPostItem.setUpdateTime(System.currentTimeMillis());
        draftsPostItem.setType("novel");
        novelDrafts.add(draftsPostItem);
        deleteModifyDraftsItem();
        SPHelper.putString(WriteArticleActivity.this, SPConstant.SPNAME_NOVELDRAFTS + uid, SPConstant.NOVEL, gson.toJson(novelDrafts));
        SPHelper.putString(WriteArticleActivity.this, SPConstant.SPNAME_NOVELDRAFTS + uid, SPConstant.NOVEL_COUNT, String.valueOf(novelDrafts.size()));
        setResult(RESULT_OK);
        finish();
    }

    private void deleteModifyDraftsItem() {
        if (null != modifyDraftsItem) {
            long modifyDraftsUpdateTime = modifyDraftsItem.getUpdateTime();
            DraftsPostItem modifyedDraftsItem = null;
            for (int i = 0; i < novelDrafts.size(); i++) {
                if (modifyDraftsUpdateTime == novelDrafts.get(i).getUpdateTime()) {
                    modifyedDraftsItem = novelDrafts.get(i);
                    break;
                }
            }
            if (null != modifyedDraftsItem)
                novelDrafts.remove(modifyedDraftsItem);
        }
    }

    private boolean checkNeedSave() {
        String content = articleContent.getText().toString().trim();
        String title = articleTitle.getText().toString().trim();
        if (TextUtils.isEmpty(content) && TextUtils.isEmpty(title)) {
            return false;
        }
        String[] contents = content.split("\n");
        List<String> listContent = Arrays.asList(contents);
        postItem.setContent(listContent);
        postItem.setTitle(title);
        return true;
    }

}
